//
//  BanBu_LocationManagerViewController.m
//  BanBu
//
//  Created by 来国 郑 on 12-7-19.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BanBu_LocationManager.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDataManager.h"
#import "ASIHTTPRequest.h"
#import <arpa/inet.h>
@implementation BanBu_LocationManager

@synthesize locationManager = _locationManager;
@synthesize curLocation = _curLocation;
@synthesize getLocation = _getLocation;
@synthesize getMyAddress = _getMyAddress;
@synthesize delegate = _delegate;


static BanBu_LocationManager *sharedLocationManager = nil;

- (void)initRaysource
{
    self.ipAdress = @"";
    if(_locationManager == nil)
        _locationManager = [[CLLocationManager alloc] init];
    if (![CLLocationManager locationServicesEnabled])
    {
        MyAppDataManager.locationServicesEnabled = NO;
    }
    {
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = 10.0f;
        //2014年10月09日09:48:00 ios8定位新方法
        if ([[[UIDevice currentDevice] systemVersion] floatValue]>=8.0)
        {
            [_locationManager requestAlwaysAuthorization]; // 永久授权
            [_locationManager requestWhenInUseAuthorization]; //使用中授权
        }
        CGPoint point = CGPointFromString([[NSUserDefaults standardUserDefaults] valueForKey:Location]);
        _curLocation = CLLocationCoordinate2DMake(point.x, point.y);
        if(!_curLocation.latitude){
            NSString *langauage=[MyAppDataManager  getPreferredLanguage];
            if([langauage isEqual:@"zh-Hans"]){
              _curLocation = CLLocationCoordinate2DMake(39.909027,116.411475);
            }

            else if ([langauage isEqual:@"ja"])
             {
                _curLocation = CLLocationCoordinate2DMake(35.678074,139.766005);
            }
            else if([langauage isEqual:@"en"])
            {
                _curLocation = CLLocationCoordinate2DMake(37.542751,-122.309593);
            }
            else if([langauage isEqual:@"ko"])
            {
                _curLocation = CLLocationCoordinate2DMake(37.565512,126.978011);
            }
            else if([langauage isEqual:@"ru"])
            {
                _curLocation = CLLocationCoordinate2DMake(55.751166,37.618440);
            }
            else if([langauage isEqual:@"fr"])
            {
                _curLocation = CLLocationCoordinate2DMake(48.856614, 2.352221);
            }
            else if([langauage isEqual:@"es"])
            {
                _curLocation = CLLocationCoordinate2DMake(19.431460, -99.132268);
            }
            else if([langauage isEqual:@"th"])
            {
                _curLocation = CLLocationCoordinate2DMake(13.727405, 100.523898);
            }
            else if([langauage isEqual:@"de"])
            {
                _curLocation = CLLocationCoordinate2DMake(52.519171, 13.406091);
            }
            
            else if([langauage isEqual:@"tr"])
            {
                _curLocation = CLLocationCoordinate2DMake(39.920770, 32.854109);
            }
            else if([langauage isEqual:@"it"])
            {
                _curLocation = CLLocationCoordinate2DMake(41.893210, 12.481430);
            }
            else if([langauage isEqual:@"vi"])
            {
                _curLocation = CLLocationCoordinate2DMake(21.032334,105.848468);
            }
            else if([langauage isEqual:@"cs"])
            {
                _curLocation = CLLocationCoordinate2DMake(50.075538, 14.437800);
            }
            else if([langauage isEqual:@"id"])
            {
                _curLocation = CLLocationCoordinate2DMake(-6.219111, 106.851780);
            }
            else if([langauage isEqual:@"mg"])
            {
                _curLocation = CLLocationCoordinate2DMake(3.133726, 101.685315);
            }
            else if([langauage isEqual:@"pt"])
            {
                _curLocation = CLLocationCoordinate2DMake(-22.904072, -43.209560);
            }
            else if([langauage isEqual:@"ro"])
            {
                _curLocation = CLLocationCoordinate2DMake(44.430973, 26.103864);
            }
            else if([langauage isEqual:@"fi"])
            {
                _curLocation = CLLocationCoordinate2DMake(60.175181, 24.953384);
            }
            else if([langauage isEqual:@"nb"])
            {
                _curLocation = CLLocationCoordinate2DMake(59.912675, 10.746452);
            }
            else if([langauage isEqual:@"sv"])
            {
                _curLocation = CLLocationCoordinate2DMake(59.327578, 18.053663);
            }
            else if([langauage isEqual:@"pl"])
            {
                _curLocation = CLLocationCoordinate2DMake(52.229715, 21.009782);
            }
            else if([langauage isEqual:@"uk"])
            {
                _curLocation = CLLocationCoordinate2DMake(50.450100, 30.523400);
            }
            else if([langauage isEqual:@"hu"])
            {
                _curLocation = CLLocationCoordinate2DMake(47.497912, 19.040234);
            }
            else if([langauage isEqual:@"da"])
            {
                _curLocation = CLLocationCoordinate2DMake(55.676096, 12.568337);
            }
            else if([langauage isEqual:@"el"])
            {
                _curLocation = CLLocationCoordinate2DMake(37.983715, 23.729309);
            }
            else if([langauage isEqual:@"nl"])
            {
                _curLocation = CLLocationCoordinate2DMake(52.370215, 4.895167);
            }
            else
            {
                _curLocation = CLLocationCoordinate2DMake(37.542751,-122.309593);
            }
        }
        [_locationManager startUpdatingLocation];
    }
}
- (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
//    NSLog(@"%@",address);
    return address;
    
}

#pragma mark - 获取位置信息
- (void)getMyLocation
{
    NSString *IP = [self getIPAddress];

    NSLog(@"%@",IP);
    NSLog(@"%@",self.ipAdress);
    
    if(self.netStatus == ReachableViaWiFi&&![IP isEqualToString:@"error"])
    {
        if([IP isEqualToString:self.ipAdress]&&!self.getLocation)
        {
            return ;
        }
    }
    
    self.getLocation = YES;
    [_locationManager startUpdatingLocation];

}

- (void)getCurrentAddress
{
    self.getMyAddress = YES;
   // [_locationManager startUpdatingLocation];
}


+ (BanBu_LocationManager *)sharedLocationManager;
{
    @synchronized(self){
        if(sharedLocationManager == nil){
            sharedLocationManager = [[[self alloc] init] autorelease];
            [sharedLocationManager initRaysource];
            // 开启定位服务
            [sharedLocationManager getMyLocation];
            
        }
    }
    return sharedLocationManager;
    
}



+(id)allocWithZone:(NSZone *)zone{
    @synchronized(self){
        if (sharedLocationManager == nil) {
            sharedLocationManager = [super allocWithZone:zone];
            return  sharedLocationManager;
        }
    }
    return nil;
}

- (void)dealloc
{
    [_locationManager release],_locationManager = nil;
    [super dealloc];
}


- (id)copyWithZone:(NSZone *)zone
{
    return self;
}
- (id)retain
{
    return self;
}
- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}
- (oneway void)release
{
    //do nothing
}
- (id)autorelease
{
    return self;
}


#pragma CLLocationManager delegate method 获取地理位置信息

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    MyAppDataManager.locationServicesEnabled = YES;
    CLLocation *newLocation = [locations lastObject];
    _curLocation = [newLocation coordinate];
    if(!_curLocation.latitude)
        _curLocation = CLLocationCoordinate2DMake(40.199230,118.331400);
    [[NSUserDefaults standardUserDefaults] setValue:NSStringFromCGPoint(CGPointMake(_curLocation.latitude, _curLocation.longitude)) forKey:Location];
    [manager stopUpdatingLocation];
    if(self.getLocation)
    {
        self.getLocation = NO;
        if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocation:success:)])
            [_delegate banBu_LocationManager:self didGetLocation:_curLocation success:YES];
    }
    
    if(self.getMyAddress==NO)
    {
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        [geocoder reverseGeocodeLocation:newLocation completionHandler:
         ^(NSArray* placemarks, NSError* error){
             self.getMyAddress = NO;
             [geocoder cancelGeocode];
             [geocoder release];
             if(error)
             {
                 if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationAddr:)])
                     [_delegate banBu_LocationManager:self didGetLocationAddr:nil];
             }
             else
             {
                 MKPlacemark *placemark = [placemarks objectAtIndex:0];
                 if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationAddr:)])
                     
                     [_delegate banBu_LocationManager:self didGetLocationAddr:[placemark name]];
             }
         }];
        
        
        //       MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:_curLocation];
        //        geocoder.delegate = self;
        //        [geocoder start];
    }

}
//- (void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
//{
//    MyAppDataManager.locationServicesEnabled = YES;
//    _curLocation = [newLocation coordinate];
//    if(!_curLocation.latitude)
//        _curLocation = CLLocationCoordinate2DMake(40.199230,118.331400);
//    [[NSUserDefaults standardUserDefaults] setValue:NSStringFromCGPoint(CGPointMake(_curLocation.latitude, _curLocation.longitude)) forKey:Location];
//    [manager stopUpdatingLocation];
//    if(self.getLocation)
//    {
//        self.getLocation = NO;
//        if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocation:success:)])
//            [_delegate banBu_LocationManager:self didGetLocation:_curLocation success:YES];
//    }
//
//    if(self.getMyAddress==NO)
//    {
//        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
//        [geocoder reverseGeocodeLocation:newLocation completionHandler:
//         ^(NSArray* placemarks, NSError* error){
//             self.getMyAddress = NO;
//             [geocoder cancelGeocode];
//             [geocoder release];
//             if(error)
//             {
//                 if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationAddr:)])
//                     [_delegate banBu_LocationManager:self didGetLocationAddr:nil];
//             }
//             else
//             {
//                 MKPlacemark *placemark = [placemarks objectAtIndex:0];
//                 if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationAddr:)])
//                     
//                     [_delegate banBu_LocationManager:self didGetLocationAddr:[placemark name]];
//             }
//         }];
//        
//        
////       MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:_curLocation];
////        geocoder.delegate = self;
////        [geocoder start];
//    }
//}



- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    MyAppDataManager.locationServicesEnabled = NO;
    [manager stopUpdatingLocation];
    
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    if (kCLAuthorizationStatusDenied == status || kCLAuthorizationStatusRestricted == status) {
    
          if([_delegate respondsToSelector:@selector(banBu_LocationManager:didShowIndelegate:)]&&_delegate)
         
          {
              [_delegate banBu_LocationManager:self didShowIndelegate:@"fuck"];
          
          }
        
        
    }
    
    if(self.getLocation)
    {
        self.getLocation = NO;
        if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocation:success:)])
            [_delegate banBu_LocationManager:self didGetLocation:_curLocation success:NO];
    }

    if(self.getMyAddress)
    {
        self.getMyAddress = NO;
        if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationAddr:)])
            [_delegate banBu_LocationManager:self didGetLocationAddr:nil];
        
    }
}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark
{
    [geocoder cancel];
    [geocoder release];
    if(self.getMyAddress)
    {
        self.getMyAddress = NO;
        if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationAddr:)])
 
            [_delegate banBu_LocationManager:self didGetLocationAddr:nil];
    
    }
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error
{
    [geocoder cancel];
    [geocoder release];
    if(self.getMyAddress)
    {
        self.getMyAddress = NO;
        if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationAddr:)])
            [_delegate banBu_LocationManager:self didGetLocationAddr:nil];
    }
}

/*- (void)didFinishLocation
{
    if(self.getLocationPic)
    {
        self.getLocationPic = NO;
        UIGraphicsBeginImageContextWithOptions(_mapView.bounds.size, YES,isRetina?2.0:1.0);
        [_mapView.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        [self.mapView removeFromSuperview];
        self.mapView = nil;
        if([_delegate respondsToSelector:@selector(banBu_LocationManager:didGetLocationPic:)])
            [_delegate banBu_LocationManager:self didGetLocationPic:image];
    }
    
}*/


@end
